<template>
  <!-- 用户编辑 -->
  <div class="container">
    <el-dialog
      title="修改密码"
      :visible.sync="dialogVisible"
      :before-close="closeDialog"
      width="20%"
    >
      <el-form
        :model="form"
        status-icon
        :rules="rules"
        ref="formRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="新密码" prop="password">
          <el-input
            type="password"
            v-model="form.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPassword">
          <el-input
            type="password"
            v-model="form.checkPassword"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { updatePassword } from "@/api/system/user.js";

export default {
  name: "EditPaaword",
  data() {
    return {
      form: {
        password: undefined,
        checkPassword: undefined,
        // 表单校验结果
        validate: false,
      },
      dialogVisible: false,
      rules: {
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        checkPassword: [
          { required: true, validator: this.validatePassword, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    validatePassword(rule, value, callback) {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    },
    // 校验表单
    validateForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.validate = true;
          return true;
        } else {
          this.validate = false;
          return false;
        }
      });
    },
    handleSave() {
      // 校验表单
      this.validateForm();
      if (!this.validate) {
        return;
      }
      updatePassword(this.form.password, this.form.checkPassword).then(
        (res) => {
          if (res.code == 200) {
            this.$modal.msgSuccess(res.msg);
            this.closeDialog();
          } else {
            this.$modal.msgError(res.msg);
          }
        }
      );
    },
    closeDialog() {
      this.form = {
        password: undefined,
        checkPassword: undefined,
      };

      this.dialogVisible = false;
    },
  },
};
</script>